package com.cwz.security.aspect;

import com.cwz.security.annotation.RequiresLogin;
import com.cwz.security.annotation.RequiresPermissions;
import com.cwz.security.annotation.RequiresRoles;
import com.cwz.security.auth.AuthUtil;
import lombok.NoArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @program: w-demo
 * @description: 权限认证 aop
 * @author: Wen
 **/
@Aspect
@Component
@NoArgsConstructor
public class PreAuthorizeAspect {

	/**
	 * 定义 AOP 签名 (切入所有使用鉴权注解的方法)
	 */
	@Pointcut("@annotation(com.cwz.security.annotation.RequiresLogin) || "
		+ "@annotation(com.cwz.security.annotation.RequiresPermissions) ||"
		+ "@annotation(com.cwz.security.annotation.RequiresRoles)")
	public void pointcut() {}

	/**
	 * 环绕切入
	 *
	 * @param joinPoint 切面对象
	 * @return 底层方法执行后的返回值
	 * @throws Throwable 底层方法抛出的异常
	 */
	@Around("pointcut()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		// 注解鉴权
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		checkMethodAnnotation(signature.getMethod());
		// 执行原有逻辑
		return joinPoint.proceed();
	}

	/**
	 * 对一个 Method 对象进行注解检查
	 */
	private void checkMethodAnnotation(Method method) {
		// 校验 @RequiresLogin 注解
		RequiresLogin requiresLogin = method.getAnnotation(RequiresLogin.class);
		if (requiresLogin != null) {
			AuthUtil.checkLogin();
		}

		// 校验 @RequiresRoles 注解
		RequiresRoles requiresRoles = method.getAnnotation(RequiresRoles.class);
		if (requiresRoles != null) {
			AuthUtil.checkRole(requiresRoles);
		}

		// 校验 @RequiresPermissions 注解
		RequiresPermissions requiresPermissions = method.getAnnotation(RequiresPermissions.class);
		if (requiresPermissions != null) {
			AuthUtil.checkPermi(requiresPermissions);
		}
	}
}
